'''
Python项目自动更新本地内存的案例
'''
from flask import Flask, jsonify, request

from model.db.name_mapping import db
from watchers.etcd_watcher import start_etcd_watch_thread
from watchers.redis_pub_sub import start_subscriber
from watchers.redis_streams import start_consumer_redis_stream
from watchers.consul_watcher import start_consul_watch
from watchers.nacos_listener import start_watch_name_mapping
from service.biz import get_student_name, get_class_name, get_school_name, get_team_name, update_name_by_type

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123@127.0.0.1:3306/cache_test?charset=utf8mb4'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)

# Notice etcd: 监听 /name_mapping/update 变更
# start_etcd_watch_thread(app)


# Notice consul: 监听 name_mapping/notify 变更
# start_consul_watch(app)

# Notice nacos: 监听指定的 GROUP-DATAId 配置变更
# start_watch_name_mapping(app)

# Notice redis发布订阅
start_subscriber(app)

# Notice redis streams
# start_consumer_redis_stream(app)


@app.route('/update_name', methods=['PUT'])
def update_name():
    '''
    curl -X PUT http://127.0.0.1:5000/update_name \
        -H "Content-Type: application/json" \
        -d '{"name_type": "student", "name": "NewStudentName"}'
    '''
    data = request.get_json()
    name_type = data.get('name_type')
    new_name = data.get('name')

    update_name_by_type(name_type, new_name)

    return jsonify({'success': True})


# curl http://127.0.0.1:5000/student_name
@app.route('/student_name')
def student_name():
    return jsonify({'student_name': get_student_name()})


# curl http://127.0.0.1:5000/class_name
@app.route('/class_name')
def class_name():
    return jsonify({'class_name': get_class_name()})


# curl http://127.0.0.1:5000/school_name
@app.route('/school_name')
def school_name():
    return jsonify({'school_name': get_school_name()})


# curl http://127.0.0.1:5000/team_name
@app.route('/team_name')
def team_name():
    return jsonify({'team_name': get_team_name()})


if __name__ == '__main__':
    app.run(debug=False, use_reloader=False)
